<template>
  <el-card class="data-management">
    <!-- 头部区域 -->
    <template #header>
      <page-header title="数据管理" />
    </template>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 上部分：导入导出区域 -->
      <div class="operation-area">
        <!-- 导出区域 -->
        <div class="export-area">
          <div class="area-title">数据导出</div>
          <div class="export-form">
            <el-form :model="exportForm">
              <!-- 字段选择 -->
              <div class="form-section">
                <div class="section-title">筛选条件 - 字段</div>
                <div class="field-tip">
                  <el-alert
                    type="info"
                    :closable="false"
                    show-icon
                  >
                    <template #default>
                      <div class="tip-content">
                        <p>勾选字段用于筛选要导出的证书：只导出同时包含所有勾选字段的证书</p>
                        <p>如果不勾选任何字段，将导出所有证书</p>
                        <p>导出时会包含证书的所有字段内容</p>
                        <p class="tip-note">注：最终导出结果会受到下方时间范围和证书状态的进一步筛选</p>
                      </div>
                    </template>
                  </el-alert>
                </div>
                <div class="fields-container">
                  <el-checkbox-group 
                    v-model="exportForm.fields"
                    id="export-fields"
                    name="export-fields"
                  >
                    <el-checkbox 
                      v-for="field in exportFields" 
                      :key="field.field_name" 
                      :value="field.field_name"
                      class="field-checkbox"
                      :id="'export-field-' + field.field_name"
                      :name="'export-field-' + field.field_name"
                    >
                      {{ field.name }}
                      <el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>

              <!-- 导出格式选择 -->
              <div class="form-section">
                <div class="section-title">导出格式</div>
                <el-radio-group 
                  v-model="exportForm.format"
                  id="export-format"
                  name="export-format"
                >
                  <el-radio value="xlsx">XLSX</el-radio>
                  <el-radio value="csv">CSV</el-radio>
                </el-radio-group>
              </div>

              <!-- 筛选条件 -->
              <div class="form-section">
                <div class="section-title">筛选条件 - 时间与状态</div>
                <div class="field-tip">
                  <el-alert
                    type="info"
                    :closable="false"
                    show-icon
                  >
                    <template #default>
                      <div class="tip-content">
                        <p>选择时间范围和证书状态来进一步筛选要导出的证书</p>
                        <p>如果不选择，则不会按这些条件进行筛选</p>
                      </div>
                    </template>
                  </el-alert>
                </div>
                <div class="filter-container">
                  <div class="filter-item">
                    <div class="filter-label">时间范围</div>
                    <el-date-picker
                      v-model="exportForm.dateRange"
                      type="daterange"
                      value-format="YYYY-MM-DD"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :shortcuts="dateShortcuts"
                      unlink-panels
                      class="date-picker"
                      :id="['export-date-range-start', 'export-date-range-end']"
                      :name="['export-date-range-start', 'export-date-range-end']"
                    />
                  </div>
                  <div class="filter-item">
                    <div class="filter-label">证书状态</div>
                    <el-select
                      v-model="exportForm.status"
                      placeholder="导出全部"
                      class="status-select"
                      id="export-status"
                      name="export-status"
                    >
                      <el-option label="导出全部" value="" />
                      <el-option label="导出启用中" value="active">
                        <span style="color: var(--el-color-success)">导出启用中</span>
                      </el-option>
                      <el-option label="导出停止中" value="inactive">
                        <span style="color: var(--el-color-danger)">导出停止中</span>
                      </el-option>
                    </el-select>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
          <!-- 导出进度和按钮 -->
          <div class="export-actions">
            <div v-if="exportProgress > 0" class="export-progress">
              <el-progress :percentage="exportProgress" />
            </div>
            <el-button type="primary" :loading="isExporting" @click="handleExport">
              {{ exportButtonText }}
            </el-button>
          </div>
        </div>

        <!-- 导入区域 -->
        <div class="import-area">
          <div class="area-title">数据导入</div>
          
          <!-- 字段选择区域 -->
          <div class="import-section">
            <div class="section-title">选择导入字段</div>
            <div class="field-tip">
              <el-alert type="info" :closable="false" show-icon>
                <div class="tip-content">
                  <p>请选择要包含的字段（{{ selectedFields.length }}/{{ maxSelectable + 1 }}）</p>
                  <p class="tip-note">注：证书编号字段为必选项</p>
                </div>
              </el-alert>
            </div>
            
            <div class="fields-container">
              <!-- 必选字段 -->
              <div class="required-fields">
                <el-checkbox 
                  v-if="certNumberField"
                  disabled 
                  :checked="true"
                  class="field-item"
                  id="cert-number-field"
                  name="cert-number-field"
                >
                  {{ certNumberField.name }}
                  <el-tag size="small" type="danger">必选</el-tag>
                </el-checkbox>
              </div>
              
              <!-- 可选字段（排除证书编号字段） -->
              <div class="optional-fields">
                <el-checkbox-group 
                  v-model="selectedFields"
                  id="import-fields"
                  name="import-fields"
                  :max="maxSelectable"
                >
                  <el-checkbox 
                    v-for="field in availableFields.filter(f => f.field_name !== certNumberField?.field_name)" 
                    :key="field.field_name" 
                    :value="field.field_name"
                    :disabled="selectedFields.length >= maxSelectable && !selectedFields.includes(field.field_name)"
                    class="field-checkbox"
                    :id="'import-field-' + field.field_name"
                    :name="'import-field-' + field.field_name"
                  >
                    {{ field.name }}
                    <el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            
            <div class="template-actions">
              <el-button type="primary" @click="handleDownloadTemplate">
                <el-icon><Download /></el-icon>
                下载导入模板
              </el-button>
              <div class="template-tip">首次使用请先下载模板查看格式要求</div>
            </div>
          </div>

          <!-- 文件上传区域 -->
          <div class="import-section">
            <div class="section-title">上传文件</div>
            <el-upload
              ref="uploadRef"
              class="upload-drop-area"
              drag
              :auto-upload="false"
              :show-file-list="true"
              :limit="1"
              :accept="SUPPORTED_FORMATS.join(',')"
              :before-upload="handleBeforeUpload"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :loading="uploadLoading"
              id="file-upload"
              name="file-upload"
            >
              <template #trigger>
                <el-icon class="upload-icon"><Upload /></el-icon>
                <div class="upload-text">
                  <span>拖拽文件到此处或点击上传</span>
                  <div class="upload-tip">支持 xlsx、xls、csv 格式，文件大小不超过10MB</div>
                </div>
              </template>

              <template #tip>
                <div v-if="uploadProgress > 0" class="upload-progress">
                  <el-progress :percentage="uploadProgress" />
                </div>
              </template>
            </el-upload>
          </div>

          <!-- 预览数据弹窗 -->
          <el-dialog
            v-model="previewDialogVisible"
            title="数据预览"
            width="80%"
            :close-on-click-modal="false"
            :destroy-on-close="true"
          >
            <div v-if="previewData.length" class="preview-content">
              <!-- 错误提示区域 -->
              <div v-if="hasErrors" class="preview-errors">
                <div v-if="redErrors.length" class="error-section">
                  <div class="error-title error-red">以下行不会导入：</div>
                  <ul class="error-list">
                    <li v-for="(error, index) in redErrors" :key="index">{{ error }}</li>
                  </ul>
                </div>
                <div v-if="yellowWarnings.length" class="error-section">
                  <div class="error-title error-yellow">以下行将会导入，但请注意：</div>
                  <ul class="error-list">
                    <li v-for="(warning, index) in processedWarnings" :key="index">{{ warning }}</li>
                  </ul>
                </div>
              </div>

              <!-- 预览表格 -->
              <el-table 
                :data="previewData" 
                stripe 
                border 
                height="400px" 
                class="preview-table"
                :row-class-name="getRowClassName"
                row-key="rowNum"
                ref="previewTableRef"
                @selection-change="handlePreviewSelectionChange"
              >
                <el-table-column 
                  type="selection" 
                  width="55"
                  :selectable="row => !row.error"
                />
                <el-table-column 
                  prop="sequence_number" 
                  label="序号" 
                  width="80"
                  class-name="sequence-number-column" 
                />
                <el-table-column
                  v-for="(col, index) in previewColumns"
                  :key="index"
                  :prop="col.prop"
                  :label="col.label"
                  :class-name="col.className"
                  show-overflow-tooltip
                />
              </el-table>

              <!-- 底部统计 -->
              <div class="preview-stats">
                <div>将导入 {{ validRowCount }} 行数据</div>
                <div v-if="newFieldsCount">新增 {{ newFieldsCount }} 个字段</div>
                <div>已选择 {{ selectedRows.length }} 行数据</div>
              </div>

              <!-- 导入进度条 -->
              <div v-if="importProgress > 0" class="import-progress">
                <el-progress :percentage="importProgress" />
              </div>
            </div>
            
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="handleCancelImport">取消导入</el-button>
                <el-button 
                  type="primary" 
                  :loading="importLoading" 
                  :disabled="importButtonDisabled"
                  @click="handleConfirmImport"
                >
                  {{ importButtonDisabled ? '无可导入数据' : '确认导入' }}
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>

      <!-- 下部分：记录列表 -->
      <div class="record-list">
        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="left">
            <el-button type="danger" :disabled="!selectedRecords.length" @click="handleBatchDelete">
              批量删除
            </el-button>
            <el-button type="primary" @click="showRetentionSettings">
              日志保留天数
            </el-button>
          </div>
          <div class="right">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              value-format="YYYY-MM-DD"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              unlink-panels
              style="width: 400px"
              :id="['search-date-range-start', 'search-date-range-end']"
              :name="['search-date-range-start', 'search-date-range-end']"
            />
            <el-select 
              v-model="searchForm.status" 
              placeholder="状态" 
              @change="handleSearch" 
              style="width: 100px"
              id="search-status"
              name="search-status"
            >
              <el-option label="全部" value="" />
              <el-option label="成功" value="成功" />
              <el-option label="失败" value="失败" />
              <el-option label="进行中" value="进行中" />
            </el-select>
            <el-select 
              v-model="searchForm.type" 
              placeholder="类型" 
              @change="handleSearch" 
              style="width: 100px"
              id="search-type"
              name="search-type"
            >
              <el-option label="全部" value="" />
              <el-option label="导入" value="导入" />
              <el-option label="导出" value="导出" />
            </el-select>
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入关键词搜索"
              style="width: 300px"
              @keyup.enter="handleSearch"
              @blur="handleSearch"
              id="search-keyword"
              name="search-keyword"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>

        <!-- 记录表格 -->
        <el-table
          :data="records"
          border
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="45" align="center" />
          <el-table-column 
            label="操作时间" 
            prop="created_at" 
            min-width="140"
            align="center"
          />
          <el-table-column 
            label="类型" 
            prop="type" 
            min-width="80"
            align="center"
          >
            <template #default="{ row }">
              <el-tag :type="row.type === '导入' ? 'success' : 'primary'" size="small">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column 
            label="文件名" 
            prop="file_name" 
            min-width="240"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column 
            label="状态" 
            prop="status" 
            min-width="80"
            align="center"
          >
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small" style="margin: 0 auto;">
                {{ row.status }}
              </el-tag>
              <span v-if="row.error_message" class="error-message" style="display: block; text-align: center; margin-top: 4px;">
                {{ row.error_message }}
              </span>
            </template>
          </el-table-column>
          <el-table-column 
            label="大小" 
            prop="file_size" 
            min-width="80"
            align="center"
          />
          <el-table-column 
            label="操作" 
            min-width="160"
            align="center"
          >
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                @click="handleDownloadFile(row)"
              >
                下载文件
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDeleteRecord(row)"
              >
                删除日志
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 统计信息 -->
        <div class="footer">
          <div class="statistics">统计信息：成功率 {{ successRate }}%</div>
        </div>
      </div>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="导入详情" width="600px">
        <template v-if="currentRecord">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="文件名">
              {{ currentRecord.file_name }}
            </el-descriptions-item>
            <el-descriptions-item label="导入时间">
              {{ currentRecord.created_at }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(currentRecord.status)">
                {{ currentRecord.status }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="总数量">
              {{ currentRecord.total_count }}
            </el-descriptions-item>
            <el-descriptions-item label="成功数量">
              {{ currentRecord.success_count }}
            </el-descriptions-item>
            <el-descriptions-item label="失败数量">
              {{ currentRecord.fail_count }}
            </el-descriptions-item>
            <el-descriptions-item label="耗时">
              {{ currentRecord.duration }}秒
            </el-descriptions-item>
            <el-descriptions-item v-if="currentRecord.error_message" label="错误信息">
              <div class="error-message">
                {{ currentRecord.error_message }}
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </template>
      </el-dialog>

      <!-- 添加模板字段选择对话框 -->
      <el-dialog
        v-model="templateDialogVisible"
        title="选择模板字段"
        width="500px"
        :close-on-click-modal="false"
      >
        <div class="field-selector">
          <div class="field-title">请选择要包含的字段（{{ selectedFields.length }}/{{ maxSelectable + 1 }}）</div>
          
          <!-- 必选字段 -->
          <div class="mb-3">
            <el-checkbox 
              v-if="certNumberField"
              disabled 
              :checked="true"
              class="field-item"
              id="cert-number-field"
              name="cert-number-field"
            >
              {{ certNumberField.name }}
              <el-tag size="small" type="danger">必选</el-tag>
            </el-checkbox>
          </div>
          
          <!-- 可选字段 -->
          <div class="mb-3">
            <el-checkbox-group 
              v-model="selectedFields"
              :max="maxSelectable"
              id="template-fields"
              name="template-fields"
            >
              <div 
                v-for="field in availableFields" 
                :key="field.field_name" 
                class="field-item"
              >
                <el-checkbox 
                  :label="field.field_name"
                  :disabled="selectedFields.length >= maxSelectable && !selectedFields.includes(field.field_name)"
                  :id="'template-field-' + field.field_name"
                  :name="'template-field-' + field.field_name"
                >
                  {{ field.name }}
                  <el-tag 
                    v-if="field.required" 
                    size="small" 
                    type="danger"
                  >
                    必填
                  </el-tag>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="templateDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDownloadTemplate">
              确认下载
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 日志保留设置对话框 -->
      <el-dialog
        v-model="retentionDialogVisible"
        title="日志保留设置"
        width="500px"
      >
        <div class="retention-form">
          <el-form :model="retentionForm" label-width="120px">
            <el-form-item label="保留天数">
              <el-input-number
                v-model="retentionForm.days"
                :min="0"
                :max="3650"
                :step="1"
                id="retention-days"
                name="retention-days"
              />
              <div class="form-tip">
                设置范围：0-3650天，默认30天<br>
                设置为0表示不自动清理
              </div>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="retentionDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveRetention">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Upload, Search, Setting } from '@element-plus/icons-vue'
import PageHeader from '@/components/PageHeader.vue'
import { dataApi } from '@/api/dataApi'
import { useFields } from '@/composables/useFields'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'

const router = useRouter()

// 支持的文件格式
const SUPPORTED_FORMATS = ['.xlsx', '.xls', '.csv']

// 数据列表
const records = ref([])
const selectedRecords = ref([])
const currentRecord = ref(null)

// 字段相关
const {
  availableFields,
  certNumberField,
  maxSelectable,
  fetchAvailableFields
} = useFields()

const selectedFields = ref([])
const exportFields = ref([])

// 上传相关
const uploadRef = ref(null)
const uploadLoading = ref(false)
const uploadProgress = ref(0)
const previewData = ref([])
const previewColumns = ref([])
const currentFile = ref(null)
const selectedRows = ref([])

// 导入相关
const importLoading = ref(false)
const importProgress = ref(0)

// 导出相关
const isExporting = ref(false)
const exportProgress = ref(0)
const exportForm = reactive({
  fields: [],
  format: 'xlsx',
  dateRange: [],
  status: ''
})

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  status: '',
  type: '',
  keyword: ''
})

// 对话框控制
const detailDialogVisible = ref(false)
const templateDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const retentionDialogVisible = ref(false)
const retentionForm = reactive({
  days: 30
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 加载字段列表
const loadFields = async () => {
  try {
    console.log('开始加载字段列表...')
    await fetchAvailableFields()
    
    // 初始化选中的字段（证书编号字段）
    if (certNumberField.value) {
      console.log('设置初始选中的证书编号字段:', certNumberField.value)
      selectedFields.value = [certNumberField.value.field_name]
    }
    
    // 设置可选字段（过滤掉证书编号字段）
    if (availableFields.value.length) {
      // 过滤掉证书编号字段，确保它不会在可选列表中出现
      exportFields.value = availableFields.value.filter(field => 
        field.field_name !== certNumberField.value?.field_name
      )
      console.log('设置导出字段:', exportFields.value)
    } else {
      console.warn('没有可用的字段')
      exportFields.value = []
    }
  } catch (error) {
    console.error('加载字段列表失败:', error)
    ElMessage.error('获取字段列表失败')
  }
}

// 导出按钮文字
const exportButtonText = computed(() => {
  return isExporting.value ? '导出中...' : '开始导出'
})

// 成功率计算
const successRate = computed(() => {
  if (!records.value.length) return '0.0'
  const successCount = records.value.filter(r => r.status === '成功').length
  return ((successCount / records.value.length) * 100).toFixed(1)
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '成功': 'success',
    '失败': 'danger',
    '进行中': 'warning',
    '已完成': 'success',
    '打包中': 'info'
  }
  return statusMap[status] || 'info'
}

// 格式化文件大小
const formatFileSize = (size) => {
  // 确保 size 是数字
  const fileSize = Number(size)
  if (!fileSize || isNaN(fileSize)) return '0 B'
  
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let convertedSize = fileSize
  
  while (convertedSize >= 1024 && index < units.length - 1) {
    convertedSize /= 1024
    index++
  }
  
  return `${convertedSize.toFixed(1)} ${units[index]}`
}

// 下载模板处理
const handleDownloadTemplate = async () => {
  try {
    console.log('开始下载模板...')
    console.log('选中的字段:', selectedFields.value)
    
    const result = await dataApi.downloadTemplate({
      fields: selectedFields.value
    })
    
    if (result.success) {
      ElMessage.success('模板下载成功')
      // 关闭对话框
      templateDialogVisible.value = false
    } else if (result.canceled) {
      console.log('用户取消了保存')
    }
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('模板下载失败')
  }
}

// 文件移除处理
const handleFileRemove = async () => {
  // 保存临时文件路径
  const tempFilePath = currentFile.value?.tempFilePath
  
  // 清空状态
  selectedRows.value = []
  currentFile.value = null
  
  // 清理临时文件
  if (tempFilePath) {
    try {
      await dataApi.cleanupTempFile(tempFilePath)
    } catch (error) {
      console.error('清理临时文件失败:', error)
    }
  }
}

// 上传前检查
const handleBeforeUpload = async (file) => {
  // 先清理之前的文件
  try {
    await dataApi.cleanupTempFile()
  } catch (error) {
    console.error('清理之前的临时文件失败:', error)
  }

  const isValidFormat = SUPPORTED_FORMATS.some(format => 
    file.name.toLowerCase().endsWith(format)
  )
  if (!isValidFormat) {
    ElMessage.error('文件格式不正确')
    // 清理上传的文件
    uploadRef.value?.clearFiles()
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB')
    // 清理上传的文件
    uploadRef.value?.clearFiles()
    return false
  }
  
  return true
}

// 文件变更处理
const handleFileChange = async (uploadFile) => {
  if (!uploadFile) return
  
  try {
    uploadLoading.value = true
    
    // 直接传递原始文件对象
    const response = await dataApi.previewImport(uploadFile.raw)
    
    if (response.code === 200 && response.data) {
      console.log('预览响应数据:', {
        warnings: response.data.warnings,
        errors: response.data.errors
      })
      
      // 重置错误信息
      redErrors.value = []
      yellowWarnings.value = []
      
      // 处理错误和警告信息
      if (response.data.errors) {
        redErrors.value = response.data.errors.map(error => {
          const match = error.match(/第(\d+)行/)
          if (!match) return error
          const actualRowNumber = parseInt(match[1]) - 1
          
          if (error.includes('证书编号为空')) {
            return `第${actualRowNumber}行证书编号值为空`
          }
          if (error.includes('证书编号已存在')) {
            return `第${actualRowNumber}行证书编号与现有证书重复`
          }
          if (error.includes('字段数量超过')) {
            return `第${actualRowNumber}行字段数量超过12个`
          }
          return error.replace(/第\d+行/, `第${actualRowNumber}行`)
        })
      }
      
      if (response.data.warnings) {
        // 先获取所有错误行的行号
        const errorLines = new Set(
          response.data.errors?.map(error => {
            const match = error.match(/第(\d+)行/)
            return match ? parseInt(match[1]) : null
          }).filter(Boolean) || []
        )

        // 只处理没有错误的行的警告
        yellowWarnings.value = response.data.warnings
          .filter(warning => {
            const match = warning.match(/第(\d+)行/)
            return match && !errorLines.has(parseInt(match[1]))
          })
          .map(warning => {
            const match = warning.match(/第(\d+)行/)
            if (!match) return warning
            const actualRowNumber = parseInt(match[1]) - 1
            
            if (warning.includes('新字段')) {
              return `第${actualRowNumber}行出现了新的字段"${warning.match(/["](.*?)["]/)[1]}"`
            }
            if (warning.includes('只有证书编号')) {
              return `第${actualRowNumber}行只有证书编号，没有其他值`
            }
            if (warning.includes('特殊字符')) {
              return `第${actualRowNumber}行包含特殊字符，将自动转换格式`
            }
            return warning.replace(/第\d+行/, `第${actualRowNumber}行`)
          })
      }

      // 设置预览数据，包含预分配的序号
      const startNum = response.data.maxSequenceNumber ? 
        parseInt(response.data.maxSequenceNumber) + 1 : 1
      
      console.log('当前最大序号:', response.data.maxSequenceNumber, '起始序号:', startNum)

      previewData.value = response.data.previewData.map((row, index) => {
        // 因为后端把字段名行算作第1行，所以这里要加2
        const fileLineNumber = index + 2  // 后端视角的行号
        const displayRowNumber = index + 1 // 前端显示的行号（从1开始）

        // 添加详细的调试日志
        console.log('行数据处理:', {
          index,
          fileLineNumber,  // 用于匹配后端错误信息的行号
          displayRowNumber, // 用于显示的行号
          row,
          hasError: response.data.errors?.some(error => {
            const matches = error.includes(`第${fileLineNumber}行`)
            console.log('错误匹配:', { fileLineNumber, error, matches })
            return matches
          }),
          hasWarning: response.data.warnings?.some(warning => {
            const matches = warning.includes(`第${fileLineNumber}行`)
            console.log('警告匹配:', { fileLineNumber, warning, matches })
            return matches
          })
        })

        return {
          ...row,
          rowNum: displayRowNumber,
          error: response.data.errors?.some(error => error.includes(`第${fileLineNumber}行`)),
          warning: response.data.warnings?.some(warning => warning.includes(`第${fileLineNumber}行`)),
          sequence_number: String(startNum + index).padStart(4, '0')
        }
      })
      
      // 转换表头为列配置（排除序号列，因为已经单独添加）
      previewColumns.value = (response.data.headers || [])
        .filter(header => header !== '序号')
        .map(header => ({
          prop: header,
          label: header,
          className: header === '证书编号' ? 'cert-number-column' : ''
        }))

      // 保存临时文件路径和新字段信息到当前文件对象
      currentFile.value = uploadFile
      if (response.data.tempFilePath) {
        currentFile.value.tempFilePath = response.data.tempFilePath
      }
      if (response.data.newFields) {
        currentFile.value.newFields = response.data.newFields
      }
      
      // 显示预览弹窗
      if (previewData.value.length > 0) {
        previewDialogVisible.value = true
        // 在下一个 tick 中设置默认选中
        nextTick(() => {
          const validRows = previewData.value.filter(row => !row.error)
          validRows.forEach(row => {
            previewTableRef.value?.toggleRowSelection(row, true)
          })
        })
      } else {
        ElMessage.warning('文件中没有数据')
        handleCancelImport()
      }
    } else {
      throw new Error('预览数据格式不正确')
    }
  } catch (error) {
    console.error('文件预览失败:', error)
    ElMessage.error(error.message || '文件预览失败')
    handleCancelImport()
  } finally {
    uploadLoading.value = false
  }
}

// 取消导入
const handleCancelImport = async () => {
  // 保存临时文件路径
  const tempFilePath = currentFile.value?.tempFilePath
  
  // 清空所有状态
  previewData.value = []
  previewColumns.value = []
  selectedRows.value = []
  
  // 清空上传组件
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  
  previewDialogVisible.value = false
  
  // 清空当前文件（在清理临时文件之后）
  currentFile.value = null
  
  // 通知后端清理临时文件
  if (tempFilePath) {
    try {
      await dataApi.cleanupTempFile(tempFilePath)
    } catch (error) {
      console.error('清理临时文件失败:', error)
    }
  }
}

// 确认导入
const handleConfirmImport = async () => {
  const startTime = new Date().getTime() // 记录开始时间的毫秒数
  try {
    importLoading.value = true
    if (!currentFile.value) {
      throw new Error('没有选择文件')
    }

    // 只发送选中的行数据
    const importData = selectedRows.value.map(row => {
      const rowData = { ...row }
      // 删除内部属性
      delete rowData.error
      delete rowData.warning
      delete rowData.warnings
      delete rowData.rowNum
      return rowData
    })

    // 创建FormData对象
    const formData = new FormData()
    
    // 验证必要参数
    if (!importData || !currentFile.value?.raw) {
      ElMessage.error('导入数据或文件不完整，请重新选择文件')
      return
    }
    
    formData.append('data', JSON.stringify(importData))
    formData.append('file', currentFile.value.raw)

    try {
      console.log('开始确认导入流程...');
      const response = await dataApi.importData(formData)
      console.log('收到导入响应:', response);

      if (response) {
        // 计算耗时（毫秒转换为秒）
        const duration = Math.round((new Date().getTime() - startTime) / 1000)
      
        // 记录成功的操作日志
        await dataApi.logOperation({
          type: '导入',
          file_name: currentFile.value.raw.name,
          file_size: currentFile.value.raw.size,
          status: '成功',
          start_time: new Date(startTime).toISOString(),
          end_time: new Date().toISOString(),
          created_at: new Date(startTime).toISOString(),
          file_path: currentFile.value.tempFilePath,
          duration: duration // 添加耗时字段
        })

        ElMessage.success(response.message || '导入成功！')
        // 关闭预览弹窗
        previewDialogVisible.value = false
        // 刷新列表
        await loadRecords()

        // 导入成功后跳转到证书列表页面
        await router.push({ name: 'CertificateList' })
        console.log('已执行跳转到 CertificateList');
      } else {
        // 处理特定类型的错误
        if (response.error?.includes('sequence_number must be unique') || 
            response.error?.includes('Duplicate entry') ||
            response.error?.includes('SequelizeUniqueConstraintError')) {
          throw new Error('导入失败：序列号生成冲突，请重试')
        } else if (response.error?.includes('transaction')) {
          throw new Error('导入失败：数据库事务错误，请重试')
        } else {
          throw new Error(response.message || '导入失败，请检查数据格式是否正确')
        }
      }
    } catch (error) {
      console.error('导入失败:', error)
      // 根据错误类型显示不同的错误信息
      if (error.message.includes('序列号')) {
        ElMessage.error('导入失败：序列号生成冲突，请重试')
      } else if (error.message.includes('事务')) {
        ElMessage.error('导入失败：系统错误，请重试')
      } else {
        ElMessage.error(error.message || '导入失败')
      }
    }
  } catch (error) {
    // 计算耗时（毫秒转换为秒）
    const duration = Math.round((new Date().getTime() - startTime) / 1000)
    
    // 记录失败的操作日志
    if (currentFile.value) {
      await dataApi.logOperation({
        type: '导入',
        file_name: currentFile.value.raw.name,
        file_size: currentFile.value.raw.size,
        status: '失败',
        error_message: error.message,
        start_time: new Date(startTime).toISOString(),
        end_time: new Date().toISOString(),
        created_at: new Date(startTime).toISOString(),
        file_path: currentFile.value.tempFilePath,
        duration: duration // 添加耗时字段
      }).catch(console.error)
    }

    console.error('导入失败:', error)
    // 根据错误类型显示不同的错误信息
    if (error.message.includes('序列号')) {
      ElMessage.error('导入失败：序列号生成冲突，请重试')
    } else if (error.message.includes('事务')) {
      ElMessage.error('导入失败：系统错误，请重试')
    } else {
      ElMessage.error(error.message || '导入失败')
    }
  } finally {
    importLoading.value = false
    importProgress.value = 0
    // 清空预览数据和文件
    await handleCancelImport()
  }
}

// 导出数据
const handleExport = async () => {
  try {
    // 生成默认文件名
    const filename = `export_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`

    isExporting.value = true
    const params = {
      fields: exportForm.fields,
      format: exportForm.format,
      status: exportForm.status,
      start_date: exportForm.dateRange?.[0],
      end_date: exportForm.dateRange?.[1],
      filename
    }
    
    // 开始导出
    exportProgress.value = 30
    const result = await dataApi.exportData(params)
    
    if (result.success) {
      exportProgress.value = 100
      ElMessage.success('导出成功')
      // 延迟一下再刷新列表，确保后端事务已提交
      await new Promise(resolve => setTimeout(resolve, 1000))
      await loadRecords()
    } else {
      throw new Error('导出失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('导出失败:', error)
      ElMessage.error(error.message || '导出失败')
    }
  } finally {
    isExporting.value = false
    // 延迟清除进度条
    setTimeout(() => {
      exportProgress.value = 0
    }, 500)
  }
}

// 选择变更
const handleSelectionChange = (selection) => {
  selectedRecords.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除选中的记录吗？', '提示', {
      type: 'warning'
    })
    await dataApi.batchDelete(selectedRecords.value.map(r => r.id))
    ElMessage.success('删除成功')
    // 刷新列表
    await loadRecords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 查看详情
const handleViewDetail = (row) => {
  currentRecord.value = row
  detailDialogVisible.value = true
}

// 下载文件
const handleDownloadFile = async (row) => {
  try {
    await dataApi.downloadRecordFile(row.id)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载失败')
  }
}

// 删除记录
const handleDeleteRecord = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此记录吗？删除后将无法恢复文件。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await dataApi.deleteRecord(row.id)
    ElMessage.success('删除成功')
    await loadRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 搜索处理
const handleSearch = async () => {
  await loadRecords()
}

// 加载记录列表
const loadRecords = async () => {
  try {
    const response = await dataApi.getRecords({
      page: 1,
      pageSize: 10,
      type: searchForm.type,
      status: searchForm.status,
      keyword: searchForm.keyword,
      start_date: searchForm.dateRange?.[0],
      end_time: searchForm.dateRange?.[1]
    })
    
    console.log('原始响应数据:', response)
    
    // 处理响应数据
    if (response?.items && Array.isArray(response.items)) {
      records.value = response.items.map(item => {
        // 确保文件大小是数字
        const fileSize = item.file_size ? Number(item.file_size) : 0
        
        // 处理耗时
        let duration = '-'
        if (item.duration) {
          // 如果耗时大于60秒，显示分钟和秒
          if (item.duration > 60) {
            const minutes = Math.floor(item.duration / 60)
            const seconds = item.duration % 60
            duration = `${minutes}分${seconds}秒`
          } else {
            duration = `${item.duration}秒`
          }
        }
          
        return {
          id: item.id,
          created_at: item.created_at ? dayjs(item.created_at).format('YYYY-MM-DD HH:mm:ss') : '-',
          type: item.type || '-', // 直接使用type字段
          file_name: item.file_name || '-',
          status: item.status || '-',
          file_size: formatFileSize(fileSize),
          duration,
          error_message: item.error_message || ''
        }
      })
      console.log('处理后的记录列表:', records.value)
    } else {
      console.warn('记录列表为空或格式不正确:', response)
      records.value = []
    }
  } catch (error) {
    console.error('获取记录列表失败:', error)
    records.value = []
    // 只在非取消操作时显示错误提示
    if (error.name !== 'CanceledError') {
      ElMessage.error('获取记录列表失败')
    }
  }
}

// 预览相关的计算属性
const hasErrors = computed(() => redErrors.value.length > 0 || yellowWarnings.value.length > 0)
const validRowCount = computed(() => previewData.value.filter(row => !row.error).length)
const newFieldsCount = computed(() => currentFile.value?.newFields?.length || 0)

// 导入按钮禁用逻辑
const importButtonDisabled = computed(() => {
  // 如果正在导入，禁用按钮
  if (importLoading.value) return true
  // 如果没有选择任何行，禁用按钮
  if (!selectedRows.value?.length) return true
  // 如果选中的行中包含错误行，禁用按钮
  if (selectedRows.value.some(row => row.error)) return true
  // 如果没有有效行可以导入，禁用按钮
  if (validRowCount.value === 0) return true
  return false
})

// 错误和警告信息
const redErrors = ref([])
const yellowWarnings = ref([])

// 优化警告信息显示
const processedWarnings = computed(() => {
  if (!yellowWarnings.value || yellowWarnings.value.length === 0) {
    return []
  }

  const lineNumbers = yellowWarnings.value.map(w => {
    const match = w.match(/第(\d+)行/)
    return match ? parseInt(match[1]) : null
  }).filter(n => n !== null).sort((a, b) => a - b)

  if (lineNumbers.length === 0) {
    return yellowWarnings.value // 如果没有匹配到行号，返回原始警告
  }

  const ranges = []
  let start = lineNumbers[0]
  let end = lineNumbers[0]

  for (let i = 1; i < lineNumbers.length; i++) {
    if (lineNumbers[i] === end + 1) {
      end = lineNumbers[i]
    } else {
      ranges.push(start === end ? `${start}` : `${start}-${end}`)
      start = lineNumbers[i]
      end = lineNumbers[i]
    }
  }
  ranges.push(start === end ? `${start}` : `${start}-${end}`)

  return [`第 ${ranges.join('、')} 行包含特殊字符，将自动转换格式`]
})

// 处理预览数据的选择变更
const handlePreviewSelectionChange = (selection) => {
  selectedRows.value = selection
  
  // 重新分配序号
  if (previewData.value.length > 0 && selection.length > 0) {
    // 获取第一个选中行的序号作为起始序号
    const firstSelectedRow = selection[0]
    const startNum = parseInt(firstSelectedRow.sequence_number)
    
    // 为选中的行重新分配序号
    selection.forEach((row, index) => {
      row.sequence_number = String(startNum + index).padStart(4, '0')
    })
    
    // 未选中的行清除序号
    previewData.value.forEach(row => {
      if (!selection.includes(row)) {
        row.sequence_number = ''
      }
    })
  }
}

// 获取行的类名
const getRowClassName = ({ row }) => {
  if (row.warning) return 'warning-row'  // 如果有警告，优先返回警告样式
  if (row.error) return 'error-row'      // 否则，如果有错误，返回错误样式
  return ''
}

// 初始化
onMounted(async () => {
  await loadFields()
  await loadRecords()
})

// 添加表格引用
const previewTableRef = ref(null)

// 显示设置对话框
const showRetentionSettings = async () => {
  try {
    const response = await dataApi.getRetentionDays()
    retentionForm.days = response.retentionDays
    retentionDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取设置失败：' + error.message)
  }
}

// 保存设置
const handleSaveRetention = async () => {
  try {
    await dataApi.setRetentionDays(retentionForm.days)
    ElMessage.success('设置保存成功')
    retentionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('保存设置失败：' + error.message)
  }
}
</script>

<style lang="scss" scoped>
.data-management {
  height: 100%;
  margin: -20px;
  
  :deep(.el-card__header) {
    padding: 0;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  :deep(.el-card__body) {
    padding: 0;
    height: calc(100% - 56px);
    overflow-y: auto;
  }
}

.content-area {
  height: 100%;
  overflow-y: auto;
}

.el-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: none;
  box-shadow: none !important;
  margin: 0 !important;

  :deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
    height: calc(100vh - 57px);
    overflow: auto;
  }
}

/* 移除卡片的内边距 */
:deep(.el-card__header) {
  padding: 0;
  border-bottom: none;
}

/* 页面标题样式 */
:deep(.page-header) {
  height: 56px;
  line-height: 56px;
  padding: 0 20px;
  border-bottom: 1px solid #e2e8f0;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 2;
}

:deep(.page-header .title) {
  font-size: 16px;
  font-weight: 500;
  color: #1e293b;
  text-align: left;
  flex: 1;
}

:deep(.page-header .header-buttons) {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

/* 操作区域布局 */
.operation-area {
  display: flex;
  gap: 20px;
  padding: 20px;
}

/* 记录列表区域 */
.record-list {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  min-height: 300px;
  display: flex;
  flex-direction: column;
  margin: 0 20px 20px;
}

/* 表格区域 */
.record-list .el-table {
  flex: 1;
  margin: 16px 0;
}

.import-area,
.export-area {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  min-height: 520px;
}

.import-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2f3d;
  margin-bottom: 16px;
}

.field-tip {
  margin-bottom: 16px;
}

.fields-container {
  background: #fff;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  padding: 16px;
}

.required-fields {
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px dashed var(--el-border-color);
}

.optional-fields :deep(.el-checkbox-group) {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
}

.field-checkbox {
  margin: 0;
  display: flex;
  align-items: center;
  min-height: 32px;
}

.field-checkbox :deep(.el-checkbox__label) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  line-height: 1.2;
  font-size: 13px;
}

.template-actions {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: 16px;
}

.template-tip {
  color: #909399;
  font-size: 13px;
}

.upload-drop-area {
  border: 2px dashed #e4e7ed;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
  background: #fff;
}

.upload-drop-area:hover {
  border-color: var(--el-color-primary);
}

.upload-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 8px;
}

.upload-text {
  color: #606266;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.preview-table {
  margin: 16px 0;
  
  :deep(.el-table__row) {
    position: relative;
    background-color: #ffffff !important;
    
    &.warning-row {
      background-color: transparent !important;
    }
    
    &.error-row {
      background-color: transparent !important;
    }

    &.error-row.warning-row {
      background-color: transparent !important;
    }

    /* 确保hover状态也是白色背景 */
    &:hover {
      background-color: #ffffff !important;
    }
  }
}

.error-section {
  margin-bottom: 16px;
  padding: 12px 16px;
  border-radius: 4px;
  
  &.error-red {
    background-color: var(--el-color-danger-light-9);
    border-left: 4px solid var(--el-color-danger);
  }
  
  &.error-yellow {
    background-color: var(--el-color-warning-light-9);
    border-left: 4px solid var(--el-color-warning);
  }
}

.error-title {
  font-weight: 500;
  margin-bottom: 8px;
  
  &.error-red {
    color: var(--el-color-danger);
  }
  
  &.error-yellow {
    color: #e6a23c;
  }
}

.error-list {
  margin: 0;
  padding-left: 20px;
  
  li {
    line-height: 1.6;
    
    &.warning {
      color: var(--el-color-warning-dark-2);
    }
  }
}

.import-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 16px;
}

.import-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .optional-fields :deep(.el-checkbox-group) {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .template-actions {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .import-section {
    padding: 16px;
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 16px;
}

.toolbar .right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.toolbar .right > * {
  margin: 0;
}

.footer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
}

.statistics {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  :deep(.page-header) {
    height: auto;
    padding: 12px 16px;
    flex-direction: row;
    gap: 12px;
    align-items: flex-start;
  }

  :deep(.page-header .title) {
    font-size: 16px;
    line-height: 40px;
    text-align: left;
  }

  .operation-area {
    padding: 12px;
    flex-direction: column;
  }

  .toolbar {
    flex-direction: column;
  }

  .toolbar .right {
    flex-wrap: wrap;
  }

  .footer {
    flex-direction: column;
    gap: 16px;
  }
}

.export-form :deep(.el-select) {
  width: 120px !important;
}

.export-form :deep(.el-date-editor) {
  width: 360px !important;
}

/* 覆盖 el-select 的默认占位符样式 */
.export-form :deep(.el-select .el-input__inner) {
  color: var(--el-text-color-primary);
}

.field-selector {
  padding: 10px;
}

.field-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #606266;
}

.field-item {
  margin: 8px 0;
}

.mb-3 {
  margin-bottom: 15px;
}

.text-right {
  text-align: right;
}

.field-selector {
  max-height: 400px;
  overflow-y: auto;
}

.field-title {
  font-weight: bold;
  margin-bottom: 16px;
  color: #606266;
}

.field-item {
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.mb-3 {
  margin-bottom: 20px;
}

:deep(.el-checkbox__label) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-tag--small) {
  margin-left: 4px;
}

.field-tip {
  margin-bottom: 16px;
}

.tip-note {
  font-size: 12px;
  margin-top: 4px;
  color: var(--el-text-color-secondary);
}

.export-form :deep(.el-alert) {
  margin-bottom: 16px;
  padding: 8px 16px;
}

.export-form :deep(.el-alert .el-alert__content) {
  padding: 0 8px;
}

.export-form :deep(.el-checkbox-group) {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 8px;
  padding: 8px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

.export-form :deep(.el-checkbox) {
  margin-right: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

.export-form :deep(.el-checkbox__label) {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .fields-container {
    max-height: 240px;
  }
  
  .field-checkbox {
    width: calc(50% - 10px);
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .export-form :deep(.el-checkbox-group) {
    grid-template-columns: repeat(2, 1fr); /* 移动端2列 */
  }
  
  .fields-container {
    max-width: 100%; /* 移动端取消最大宽度限制 */
  }
  
  .export-form .el-form-item:first-child {
    margin-left: 0; /* 移动端不需要偏移 */
    width: 100%;
  }
}

.export-area {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.area-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f2f3d;
  margin-bottom: 20px;
}

.export-form {
  background: #f8fafc;
  padding: 20px;
  border-radius: 8px;
}

/* 表单区域样式 */
.form-section {
  margin-bottom: 24px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2f3d;
  margin-bottom: 12px;
}

/* 字段选择区域 */
.fields-container {
  background: #fff;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  padding: 12px;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.field-tip {
  margin: 0 auto 16px;
  max-width: 800px;
}

.tip-content {
  font-size: 13px;
  line-height: 1.5;
}

.tip-note {
  font-size: 12px;
  margin-top: 4px;
  color: var(--el-text-color-secondary);
}

/* 复选框组样式 */
.export-form :deep(.el-checkbox-group) {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  width: 100%;
}

.field-checkbox {
  margin: 0;
  display: flex;
  align-items: center;
  width: 100%;
  min-height: 28px;
}

.field-checkbox :deep(.el-checkbox__label) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  width: 100%;
  overflow: visible;
  white-space: normal;
  line-height: 1.2;
  font-size: 13px;
}

/* 筛选条件样式 */
.filter-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  width: 100%;
}

.filter-label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.date-picker {
  width: 100% !important;
}

.status-select {
  width: 100% !important;
}

/* 导出操作区域 */
.export-actions {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 12px;
}

.export-progress {
  width: 100%;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .export-form {
    padding: 16px;
  }

  .export-form :deep(.el-checkbox-group) {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .fields-container {
    max-width: 100%;
  }
  
  .filter-container {
    flex-direction: column;
  }
  
  .filter-item {
    width: 100%;
  }
}

.status-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-left: 8px;
  word-break: break-all;
}

/* 预览弹窗样式 */
.preview-content {
  .preview-tip {
    margin-bottom: 16px;
  }

  .preview-table {
    margin: 16px 0;
  }

  .import-progress {
    margin-top: 16px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: calc(90vh - 150px);
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 预览错误提示样式 */
.preview-errors {
  margin-bottom: 16px;
  
  .error-section {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .error-title {
    font-weight: 500;
    margin-bottom: 8px;
    
    &.error-red {
      color: var(--el-color-danger);
    }
    
    &.error-yellow {
      color: #e6a23c;
    }
  }
  
  .error-list {
    margin: 0;
    padding-left: 20px;
    
    li {
      margin-bottom: 4px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

/* 预览表格行样式 */
:deep(.error-row) {
  background-color: var(--el-color-danger-light-9);
}

:deep(.warning-row) {
  background-color: var(--el-color-warning-light-9);
}

/* 预览统计信息 */
.preview-stats {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  gap: 24px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.retention-form {
  padding: 20px;
}

.form-tip {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  line-height: 1.5;
}

.dialog-footer {
  padding: 20px 0 0;
}

.toolbar .left {
  display: flex;
  gap: 12px;
  align-items: center;
}
</style>